import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/cache_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/login.dart';
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MineSettingPage extends StatelessWidget {

  _showAuthorityScope(BuildContext context){
    AlertTool.showChildDialog(context, 
      _SettingAuthoritySelectWidget()
    );
  }

  _exitLogin(BuildContext context, [bool isjump = false]) async {
    RongcloudImPlugin.disconnect(false);
    SharedPreferences share = await SharedPreferences.getInstance();
    share.clear();
    RongcloudImPlugin.disconnect(false);
    if(isjump) {
      Navigator.of(context).pushAndRemoveUntil(
        PageTransition(
          type: PageTransitionType.fade,
          child: LoginScreen()
        ),(route) => false
      );
    } else {
      // eventBus.commit(KEY_TAB_CHANGE, null);
      EventMineBus.instance.commit(EventMineKeys.ExitLogin, null);
      Navigator.of(context).pop();
    }
    
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text("系统设置"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            MineSettingCell("账号管理",callback: () => Navigator.of(context).pushNamed("/settingaccount")),
            MineSettingCell("消息通知",callback: () => Navigator.of(context).pushNamed("/settingnotifier")),
            MineSettingCell("允许朋友查看x区的范围", callback: () => _showAuthorityScope(context)),
            MineSettingCell("提示音设置"),
            MineSettingCell("黑名单", callback: () => Navigator.of(context).pushNamed("/settingblacklist")),
            _MineSettingClear(),
            MineSettingCell("关于找他", callback: () => Navigator.of(context).pushNamed("/settingabout"),),
            MineSettingCell("意见与反馈"),
            SizedBox(height: 95),
            GestureDetector(
              onTap: (){
                AlertTool.showConfirmDialog(context, title: "确定要退出切换账号",sureCallback:()=>_exitLogin(context, true));
              },
              child: Container(
                width: size.width * 0.7,
                padding: const EdgeInsets.symmetric(vertical: 8),
                alignment: Alignment.center,
                child: Text("切换账号",style: instanceTextStyle(14, Colors.white),),
                decoration: BoxDecoration(
                  color: APP_main_color,
                  borderRadius: BorderRadius.circular(20)
                ),
              ),
            ),
            GestureDetector(
              onTap: (){
                AlertTool.showConfirmDialog(context, title: "确定要退出登陆",sureCallback:()=>_exitLogin(context));
              },
              child: Container(
                margin: const EdgeInsets.only(top: 10),
                padding: const EdgeInsets.symmetric(vertical: 8),
                width: size.width * 0.7,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  border: Border.all(color:APP_font_black, width: 0.5),
                  borderRadius: BorderRadius.circular(20)
                ),
                child: Text("退出",style: instanceTextStyle(14, APP_font_black)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _SettingAuthoritySelectWidget extends StatefulWidget {
  const _SettingAuthoritySelectWidget({
    Key key,
  }) : super(key: key);

  @override
  __SettingAuthoritySelectWidgetState createState() => __SettingAuthoritySelectWidgetState();
}

class __SettingAuthoritySelectWidgetState extends State<_SettingAuthoritySelectWidget> {

  bool is_halfyear = false;
  bool is_month = false;
  bool is_day = false;
  bool is_all = false;
  // xzonet 0全部 1三天 2一个月 3半年
  static const String KeyZone = "KeyZoneFriendcanlookme";

  @override
  void initState() {
    super.initState();

    SharedPreferences.getInstance().then((value) {
      int tag = value.getInt(KeyZone);
      switch (tag) {
        case 0:
          is_all = true;
          break;
        case 1:
          is_day = true;
          break;
          case 2:
          is_month = true;
          break;
        case 3:
          is_halfyear = true;
          break;
      }

      setState(() {
        
      });
    });
  }
  _clear() {
    is_halfyear = false;
    is_month = false;
    is_day = false;
    is_all = false;
  }


  _request(int xzonet) {

    Networktool.request(API.edit, params: {"xzonet": xzonet == 0 ? 'all' : xzonet}, success: (data){
      print(data);
      if(data["data"] != null) {
        SharedPreferences.getInstance().then((value) {
          value.setInt(KeyZone, xzonet);
        });
        AlertTool.showToast("修改成功");
      }
    },
    fail: (msg) => AlertTool.showToast(msg));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 12, left: 23, right: 23),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5)
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.only(bottom: 23),
            child: Text("允许朋友查看X区的范围", style: instanceTextStyle(15, APP_font_black, fontWeight: FontWeight.bold),),
          ),
          _SettingSelectRow(title: "最近半年",isselect: is_halfyear,onTap: (){
            _clear();
            setState(() {
              is_halfyear = !is_halfyear;
            });
            _request(3);
          },),
          SizedBox(height: 10,),
          _SettingSelectRow(title: "最近一个月",isselect: is_month,onTap: (){
            _clear();
            setState(() {
              is_month = !is_month;
            });
            _request(2);
          },),
          SizedBox(height: 10,),
          _SettingSelectRow(title: "最近三天",isselect: is_day,onTap: (){
             _clear();
            setState(() {
              is_day = !is_day;
            });
            _request(1);
          },),
          SizedBox(height: 10,),
          _SettingSelectRow(title: "全部",isselect: is_all, onTap: (){
             _clear();
            setState(() {
              is_all = !is_all;
            });
            _request(0);
          },),
          SizedBox(height: 30,),
          Divider(color: Color(0xffdddddd),height: 0.5,indent: 22,endIndent: 22,),
          FlatButton(
            onPressed: (){
              Navigator.of(context).pop();
            },
            child: Text("取消", style: instanceTextStyle(14, APP_font_black),),
          )
        ],
      ),
    );
  }
}

class _SettingSelectRow extends StatelessWidget {

  final String title;
  final bool isselect;
  final Function onTap;

  const _SettingSelectRow({Key key, 
    this.title, 
    this.isselect = false,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        if(onTap != null) onTap();
      },
      child: Row(
              children: [
                SelectIconWidget(width: 14,isselect: isselect),
                SizedBox(width: 10,),
                Expanded(child: Text(title, style: instanceTextStyle(14, APP_font_black),),)
              ],
            ),
    );
  }
}

class _MineSettingClear extends StatefulWidget {
  @override
  __MineSettingClearState createState() => __MineSettingClearState();
}

class __MineSettingClearState extends State<_MineSettingClear> {

  String cache = "0.0M";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initData();
  }

  _initData() async {
    double val = await CacheTool.loadCache();
    val = val / 1024 / 1024;
    setState(() {
      cache = val.toStringAsFixed(2) + "M";
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        AlertTool.showLoadingDialog(context,"正在清除");
        bool res = await CacheTool.clearCache();
        Navigator.of(context).pop();
        if(res == true) _initData();
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 9.5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(child: Text("清除缓存", style: instanceTextStyle(14, APP_font_black),)),
            Padding(
              padding: const EdgeInsets.only(right:8.0),
              child: Text(cache, style: instanceTextStyle(11, const Color(0xff999999)),),
            ),
            Image.asset("assets/my-next.png")
          ],
        ),
      ),
    );
  }
}

 class MineSettingCell extends StatelessWidget {
   final Function callback;
   final String title;
   final String detail;

  const MineSettingCell(
    this.title,
    {
    Key key, 
    this.callback, 
    this.detail = ""
    }) : super(key: key);

    @override
    Widget build(BuildContext context) {
      return GestureDetector(
        onTap: callback,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 9.5),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(child: Text(title, style: instanceTextStyle(14, APP_font_black),)),
              Padding(
                padding: const EdgeInsets.only(right:10.0),
                child: Text(detail, style: instanceTextStyle(11, const Color(0xff999999)),),
              ),
              Image.asset("assets/my-next.png")
            ],
          ),
        ),
      );
    }
  }